{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nTranslation with a Sequence to Sequence Network and Attention\n*************************************************************\n**Author**: `Sean Robertson <https://github.com/spro/practical-pytorch>`_\n\nIn this project we will be teaching a neural network to translate from\nFrench to English.\n\n::\n\n    [KEY: > input, = target, < output]\n\n    > il est en train de peindre un tableau .\n    = he is painting a picture .\n    < he is painting a picture .\n\n    > pourquoi ne pas essayer ce vin delicieux ?\n    = why not try that delicious wine ?\n    < why not try that delicious wine ?\n\n    > elle n est pas poete mais romanciere .\n    = she is not a poet but a novelist .\n    < she not not a poet but a novelist .\n\n    > vous etes trop maigre .\n    = you re too skinny .\n    < you re all alone .\n\n... to varying degrees of success.\n\nThis is made possible by the simple but powerful idea of the `sequence\nto sequence network <https://arxiv.org/abs/1409.3215>`__, in which two\nrecurrent neural networks work together to transform one sequence to\nanother. An encoder network condenses an input sequence into a vector,\nand a decoder network unfolds that vector into a new sequence.\n\n.. figure:: /_static/img/seq-seq-images/seq2seq.png\n   :alt:\n\nTo improve upon this model we'll use an `attention\nmechanism <https://arxiv.org/abs/1409.0473>`__, which lets the decoder\nlearn to focus over a specific range of the input sequence.\n\n**Recommended Reading:**\n\nI assume you have at least installed PyTorch, know Python, and\nunderstand Tensors:\n\n-  https://pytorch.org/ For installation instructions\n-  :doc:`/beginner/deep_learning_60min_blitz` to get started with PyTorch in general\n-  :doc:`/beginner/pytorch_with_examples` for a wide and deep overview\n-  :doc:`/beginner/former_torchies_tutorial` if you are former Lua Torch user\n\n\nIt would also be useful to know about Sequence to Sequence networks and\nhow they work:\n\n-  `Learning Phrase Representations using RNN Encoder-Decoder for\n   Statistical Machine Translation <https://arxiv.org/abs/1406.1078>`__\n-  `Sequence to Sequence Learning with Neural\n   Networks <https://arxiv.org/abs/1409.3215>`__\n-  `Neural Machine Translation by Jointly Learning to Align and\n   Translate <https://arxiv.org/abs/1409.0473>`__\n-  `A Neural Conversational Model <https://arxiv.org/abs/1506.05869>`__\n\nYou will also find the previous tutorials on\n:doc:`/intermediate/char_rnn_classification_tutorial`\nand :doc:`/intermediate/char_rnn_generation_tutorial`\nhelpful as those concepts are very similar to the Encoder and Decoder\nmodels, respectively.\n\nAnd for more, read the papers that introduced these topics:\n\n-  `Learning Phrase Representations using RNN Encoder-Decoder for\n   Statistical Machine Translation <https://arxiv.org/abs/1406.1078>`__\n-  `Sequence to Sequence Learning with Neural\n   Networks <https://arxiv.org/abs/1409.3215>`__\n-  `Neural Machine Translation by Jointly Learning to Align and\n   Translate <https://arxiv.org/abs/1409.0473>`__\n-  `A Neural Conversational Model <https://arxiv.org/abs/1506.05869>`__\n\n\n**Requirements**\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Loading data files\n==================\n\nThe data for this project is a set of many thousands of English to\nFrench translation pairs.\n\n`This question on Open Data Stack\nExchange <https://opendata.stackexchange.com/questions/3888/dataset-of-sentences-translated-into-many-languages>`__\npointed me to the open translation site https://tatoeba.org/ which has\ndownloads available at https://tatoeba.org/eng/downloads - and better\nyet, someone did the extra work of splitting language pairs into\nindividual text files here: https://www.manythings.org/anki/\n\nThe English to French pairs are too big to include in the repo, so\ndownload to ``data/eng-fra.txt`` before continuing. The file is a tab\nseparated list of translation pairs:\n\n::\n\n    I am cold.    J'ai froid.\n\n.. Note::\n   Download the data from\n   `here <https://download.pytorch.org/tutorial/data.zip>`_\n   and extract it to the current directory.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Similar to the character encoding used in the character-level RNN\ntutorials, we will be representing each word in a language as a one-hot\nvector, or giant vector of zeros except for a single one (at the index\nof the word). Compared to the dozens of characters that might exist in a\nlanguage, there are many many more words, so the encoding vector is much\nlarger. We will however cheat a bit and trim the data to only use a few\nthousand words per language.\n\n.. figure:: /_static/img/seq-seq-images/word-encoding.png\n   :alt:\n\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We'll need a unique index per word to use as the inputs and targets of\nthe networks later. To keep track of all this we will use a helper class\ncalled ``Lang`` which has word \u2192 index (``word2index``) and index \u2192 word\n(``index2word``) dictionaries, as well as a count of each word\n``word2count`` to use to later replace rare words.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "SOS_token = 0\nEOS_token = 1\n\n\nclass Lang:\n    def __init__(self, name):\n        self.name = name\n        self.word2index = {}\n        self.word2count = {}\n        self.index2word = {0: \"SOS\", 1: \"EOS\"}\n        self.n_words = 2  # Count SOS and EOS\n\n    def addSentence(self, sentence):\n        for word in sentence.split(' '):\n            self.addWord(word)\n\n    def addWord(self, word):\n        if word not in self.word2index:\n            self.word2index[word] = self.n_words\n            self.word2count[word] = 1\n            self.index2word[self.n_words] = word\n            self.n_words += 1\n        else:\n            self.word2count[word] += 1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The files are all in Unicode, to simplify we will turn Unicode\ncharacters to ASCII, make everything lowercase, and trim most\npunctuation.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Turn a Unicode string to plain ASCII, thanks to\n# https://stackoverflow.com/a/518232/2809427\ndef unicodeToAscii(s):\n    return ''.join(\n        c for c in unicodedata.normalize('NFD', s)\n        if unicodedata.category(c) != 'Mn'\n    )\n\n# Lowercase, trim, and remove non-letter characters\n\n\ndef normalizeString(s):\n    s = unicodeToAscii(s.lower().strip())\n    s = re.sub(r\"([.!?])\", r\" \\1\", s)\n    s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n    return s"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To read the data file we will split the file into lines, and then split\nlines into pairs. The files are all English \u2192 Other Language, so if we\nwant to translate from Other Language \u2192 English I added the ``reverse``\nflag to reverse the pairs.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def readLangs(lang1, lang2, reverse=False):\n    print(\"Reading lines...\")\n\n    # Read the file and split into lines\n    lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\\\n        read().strip().split('\\n')\n\n    # Split every line into pairs and normalize\n    pairs = [[normalizeString(s) for s in l.split('\\t')] for l in lines]\n\n    # Reverse pairs, make Lang instances\n    if reverse:\n        pairs = [list(reversed(p)) for p in pairs]\n        input_lang = Lang(lang2)\n        output_lang = Lang(lang1)\n    else:\n        input_lang = Lang(lang1)\n        output_lang = Lang(lang2)\n\n    return input_lang, output_lang, pairs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Since there are a *lot* of example sentences and we want to train\nsomething quickly, we'll trim the data set to only relatively short and\nsimple sentences. Here the maximum length is 10 words (that includes\nending punctuation) and we're filtering to sentences that translate to\nthe form \"I am\" or \"He is\" etc. (accounting for apostrophes replaced\nearlier).\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "MAX_LENGTH = 10\n\neng_prefixes = (\n    \"i am \", \"i m \",\n    \"he is\", \"he s \",\n    \"she is\", \"she s \",\n    \"you are\", \"you re \",\n    \"we are\", \"we re \",\n    \"they are\", \"they re \"\n)\n\n\ndef filterPair(p):\n    return len(p[0].split(' ')) < MAX_LENGTH and \\\n        len(p[1].split(' ')) < MAX_LENGTH and \\\n        p[1].startswith(eng_prefixes)\n\n\ndef filterPairs(pairs):\n    return [pair for pair in pairs if filterPair(pair)]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The full process for preparing the data is:\n\n-  Read text file and split into lines, split lines into pairs\n-  Normalize text, filter by length and content\n-  Make word lists from sentences in pairs\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def prepareData(lang1, lang2, reverse=False):\n    input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse)\n    print(\"Read %s sentence pairs\" % len(pairs))\n    pairs = filterPairs(pairs)\n    print(\"Trimmed to %s sentence pairs\" % len(pairs))\n    print(\"Counting words...\")\n    for pair in pairs:\n        input_lang.addSentence(pair[0])\n        output_lang.addSentence(pair[1])\n    print(\"Counted words:\")\n    print(input_lang.name, input_lang.n_words)\n    print(output_lang.name, output_lang.n_words)\n    return input_lang, output_lang, pairs\n\n\ninput_lang, output_lang, pairs = prepareData('eng', 'fra', True)\nprint(random.choice(pairs))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The Seq2Seq Model\n=================\n\nA Recurrent Neural Network, or RNN, is a network that operates on a\nsequence and uses its own output as input for subsequent steps.\n\nA `Sequence to Sequence network <https://arxiv.org/abs/1409.3215>`__, or\nseq2seq network, or `Encoder Decoder\nnetwork <https://arxiv.org/pdf/1406.1078v3.pdf>`__, is a model\nconsisting of two RNNs called the encoder and decoder. The encoder reads\nan input sequence and outputs a single vector, and the decoder reads\nthat vector to produce an output sequence.\n\n.. figure:: /_static/img/seq-seq-images/seq2seq.png\n   :alt:\n\nUnlike sequence prediction with a single RNN, where every input\ncorresponds to an output, the seq2seq model frees us from sequence\nlength and order, which makes it ideal for translation between two\nlanguages.\n\nConsider the sentence \"Je ne suis pas le chat noir\" \u2192 \"I am not the\nblack cat\". Most of the words in the input sentence have a direct\ntranslation in the output sentence, but are in slightly different\norders, e.g. \"chat noir\" and \"black cat\". Because of the \"ne/pas\"\nconstruction there is also one more word in the input sentence. It would\nbe difficult to produce a correct translation directly from the sequence\nof input words.\n\nWith a seq2seq model the encoder creates a single vector which, in the\nideal case, encodes the \"meaning\" of the input sequence into a single\nvector \u2014 a single point in some N dimensional space of sentences.\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The Encoder\n-----------\n\nThe encoder of a seq2seq network is a RNN that outputs some value for\nevery word from the input sentence. For every input word the encoder\noutputs a vector and a hidden state, and uses the hidden state for the\nnext input word.\n\n.. figure:: /_static/img/seq-seq-images/encoder-network.png\n   :alt:\n\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class EncoderRNN(nn.Module):\n    def __init__(self, input_size, hidden_size):\n        super(EncoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n\n        self.embedding = nn.Embedding(input_size, hidden_size)\n        self.gru = nn.GRU(hidden_size, hidden_size)\n\n    def forward(self, input, hidden):\n        embedded = self.embedding(input).view(1, 1, -1)\n        output = embedded\n        output, hidden = self.gru(output, hidden)\n        return output, hidden\n\n    def initHidden(self):\n        return torch.zeros(1, 1, self.hidden_size, device=device)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The Decoder\n-----------\n\nThe decoder is another RNN that takes the encoder output vector(s) and\noutputs a sequence of words to create the translation.\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Simple Decoder\n^^^^^^^^^^^^^^\n\nIn the simplest seq2seq decoder we use only last output of the encoder.\nThis last output is sometimes called the *context vector* as it encodes\ncontext from the entire sequence. This context vector is used as the\ninitial hidden state of the decoder.\n\nAt every step of decoding, the decoder is given an input token and\nhidden state. The initial input token is the start-of-string ``<SOS>``\ntoken, and the first hidden state is the context vector (the encoder's\nlast hidden state).\n\n.. figure:: /_static/img/seq-seq-images/decoder-network.png\n   :alt:\n\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class DecoderRNN(nn.Module):\n    def __init__(self, hidden_size, output_size):\n        super(DecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n\n        self.embedding = nn.Embedding(output_size, hidden_size)\n        self.gru = nn.GRU(hidden_size, hidden_size)\n        self.out = nn.Linear(hidden_size, output_size)\n        self.softmax = nn.LogSoftmax(dim=1)\n\n    def forward(self, input, hidden):\n        output = self.embedding(input).view(1, 1, -1)\n        output = F.relu(output)\n        output, hidden = self.gru(output, hidden)\n        output = self.softmax(self.out(output[0]))\n        return output, hidden\n\n    def initHidden(self):\n        return torch.zeros(1, 1, self.hidden_size, device=device)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "I encourage you to train and observe the results of this model, but to\nsave space we'll be going straight for the gold and introducing the\nAttention Mechanism.\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Attention Decoder\n^^^^^^^^^^^^^^^^^\n\nIf only the context vector is passed betweeen the encoder and decoder,\nthat single vector carries the burden of encoding the entire sentence.\n\nAttention allows the decoder network to \"focus\" on a different part of\nthe encoder's outputs for every step of the decoder's own outputs. First\nwe calculate a set of *attention weights*. These will be multiplied by\nthe encoder output vectors to create a weighted combination. The result\n(called ``attn_applied`` in the code) should contain information about\nthat specific part of the input sequence, and thus help the decoder\nchoose the right output words.\n\n.. figure:: https://i.imgur.com/1152PYf.png\n   :alt:\n\nCalculating the attention weights is done with another feed-forward\nlayer ``attn``, using the decoder's input and hidden state as inputs.\nBecause there are sentences of all sizes in the training data, to\nactually create and train this layer we have to choose a maximum\nsentence length (input length, for encoder outputs) that it can apply\nto. Sentences of the maximum length will use all the attention weights,\nwhile shorter sentences will only use the first few.\n\n.. figure:: /_static/img/seq-seq-images/attention-decoder-network.png\n   :alt:\n\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class AttnDecoderRNN(nn.Module):\n    def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):\n        super(AttnDecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        self.output_size = output_size\n        self.dropout_p = dropout_p\n        self.max_length = max_length\n\n        self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n        self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n        self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n        self.dropout = nn.Dropout(self.dropout_p)\n        self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n        self.out = nn.Linear(self.hidden_size, self.output_size)\n\n    def forward(self, input, hidden, encoder_outputs):\n        embedded = self.embedding(input).view(1, 1, -1)\n        embedded = self.dropout(embedded)\n\n        attn_weights = F.softmax(\n            self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n        attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n                                 encoder_outputs.unsqueeze(0))\n\n        output = torch.cat((embedded[0], attn_applied[0]), 1)\n        output = self.attn_combine(output).unsqueeze(0)\n\n        output = F.relu(output)\n        output, hidden = self.gru(output, hidden)\n\n        output = F.log_softmax(self.out(output[0]), dim=1)\n        return output, hidden, attn_weights\n\n    def initHidden(self):\n        return torch.zeros(1, 1, self.hidden_size, device=device)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>There are other forms of attention that work around the length\n  limitation by using a relative position approach. Read about \"local\n  attention\" in `Effective Approaches to Attention-based Neural Machine\n  Translation <https://arxiv.org/abs/1508.04025>`__.</p></div>\n\nTraining\n========\n\nPreparing Training Data\n-----------------------\n\nTo train, for each pair we will need an input tensor (indexes of the\nwords in the input sentence) and target tensor (indexes of the words in\nthe target sentence). While creating these vectors we will append the\nEOS token to both sequences.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def indexesFromSentence(lang, sentence):\n    return [lang.word2index[word] for word in sentence.split(' ')]\n\n\ndef tensorFromSentence(lang, sentence):\n    indexes = indexesFromSentence(lang, sentence)\n    indexes.append(EOS_token)\n    return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n\n\ndef tensorsFromPair(pair):\n    input_tensor = tensorFromSentence(input_lang, pair[0])\n    target_tensor = tensorFromSentence(output_lang, pair[1])\n    return (input_tensor, target_tensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Training the Model\n------------------\n\nTo train we run the input sentence through the encoder, and keep track\nof every output and the latest hidden state. Then the decoder is given\nthe ``<SOS>`` token as its first input, and the last hidden state of the\nencoder as its first hidden state.\n\n\"Teacher forcing\" is the concept of using the real target outputs as\neach next input, instead of using the decoder's guess as the next input.\nUsing teacher forcing causes it to converge faster but `when the trained\nnetwork is exploited, it may exhibit\ninstability <http://minds.jacobs-university.de/sites/default/files/uploads/papers/ESNTutorialRev.pdf>`__.\n\nYou can observe outputs of teacher-forced networks that read with\ncoherent grammar but wander far from the correct translation -\nintuitively it has learned to represent the output grammar and can \"pick\nup\" the meaning once the teacher tells it the first few words, but it\nhas not properly learned how to create the sentence from the translation\nin the first place.\n\nBecause of the freedom PyTorch's autograd gives us, we can randomly\nchoose to use teacher forcing or not with a simple if statement. Turn\n``teacher_forcing_ratio`` up to use more of it.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "teacher_forcing_ratio = 0.5\n\n\ndef train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n    encoder_hidden = encoder.initHidden()\n\n    encoder_optimizer.zero_grad()\n    decoder_optimizer.zero_grad()\n\n    input_length = input_tensor.size(0)\n    target_length = target_tensor.size(0)\n\n    encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n    loss = 0\n\n    for ei in range(input_length):\n        encoder_output, encoder_hidden = encoder(\n            input_tensor[ei], encoder_hidden)\n        encoder_outputs[ei] = encoder_output[0, 0]\n\n    decoder_input = torch.tensor([[SOS_token]], device=device)\n\n    decoder_hidden = encoder_hidden\n\n    use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n    if use_teacher_forcing:\n        # Teacher forcing: Feed the target as the next input\n        for di in range(target_length):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            loss += criterion(decoder_output, target_tensor[di])\n            decoder_input = target_tensor[di]  # Teacher forcing\n\n    else:\n        # Without teacher forcing: use its own predictions as the next input\n        for di in range(target_length):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            topv, topi = decoder_output.topk(1)\n            decoder_input = topi.squeeze().detach()  # detach from history as input\n\n            loss += criterion(decoder_output, target_tensor[di])\n            if decoder_input.item() == EOS_token:\n                break\n\n    loss.backward()\n\n    encoder_optimizer.step()\n    decoder_optimizer.step()\n\n    return loss.item() / target_length"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This is a helper function to print time elapsed and estimated time\nremaining given the current time and progress %.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import time\nimport math\n\n\ndef asMinutes(s):\n    m = math.floor(s / 60)\n    s -= m * 60\n    return '%dm %ds' % (m, s)\n\n\ndef timeSince(since, percent):\n    now = time.time()\n    s = now - since\n    es = s / (percent)\n    rs = es - s\n    return '%s (- %s)' % (asMinutes(s), asMinutes(rs))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The whole training process looks like this:\n\n-  Start a timer\n-  Initialize optimizers and criterion\n-  Create set of training pairs\n-  Start empty losses array for plotting\n\nThen we call ``train`` many times and occasionally print the progress (%\nof examples, time so far, estimated time) and average loss.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):\n    start = time.time()\n    plot_losses = []\n    print_loss_total = 0  # Reset every print_every\n    plot_loss_total = 0  # Reset every plot_every\n\n    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n    training_pairs = [tensorsFromPair(random.choice(pairs))\n                      for i in range(n_iters)]\n    criterion = nn.NLLLoss()\n\n    for iter in range(1, n_iters + 1):\n        training_pair = training_pairs[iter - 1]\n        input_tensor = training_pair[0]\n        target_tensor = training_pair[1]\n\n        loss = train(input_tensor, target_tensor, encoder,\n                     decoder, encoder_optimizer, decoder_optimizer, criterion)\n        print_loss_total += loss\n        plot_loss_total += loss\n\n        if iter % print_every == 0:\n            print_loss_avg = print_loss_total / print_every\n            print_loss_total = 0\n            print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),\n                                         iter, iter / n_iters * 100, print_loss_avg))\n\n        if iter % plot_every == 0:\n            plot_loss_avg = plot_loss_total / plot_every\n            plot_losses.append(plot_loss_avg)\n            plot_loss_total = 0\n\n    showPlot(plot_losses)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plotting results\n----------------\n\nPlotting is done with matplotlib, using the array of loss values\n``plot_losses`` saved while training.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nplt.switch_backend('agg')\nimport matplotlib.ticker as ticker\nimport numpy as np\n\n\ndef showPlot(points):\n    plt.figure()\n    fig, ax = plt.subplots()\n    # this locator puts ticks at regular intervals\n    loc = ticker.MultipleLocator(base=0.2)\n    ax.yaxis.set_major_locator(loc)\n    plt.plot(points)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Evaluation\n==========\n\nEvaluation is mostly the same as training, but there are no targets so\nwe simply feed the decoder's predictions back to itself for each step.\nEvery time it predicts a word we add it to the output string, and if it\npredicts the EOS token we stop there. We also store the decoder's\nattention outputs for display later.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n    with torch.no_grad():\n        input_tensor = tensorFromSentence(input_lang, sentence)\n        input_length = input_tensor.size()[0]\n        encoder_hidden = encoder.initHidden()\n\n        encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n        for ei in range(input_length):\n            encoder_output, encoder_hidden = encoder(input_tensor[ei],\n                                                     encoder_hidden)\n            encoder_outputs[ei] += encoder_output[0, 0]\n\n        decoder_input = torch.tensor([[SOS_token]], device=device)  # SOS\n\n        decoder_hidden = encoder_hidden\n\n        decoded_words = []\n        decoder_attentions = torch.zeros(max_length, max_length)\n\n        for di in range(max_length):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            decoder_attentions[di] = decoder_attention.data\n            topv, topi = decoder_output.data.topk(1)\n            if topi.item() == EOS_token:\n                decoded_words.append('<EOS>')\n                break\n            else:\n                decoded_words.append(output_lang.index2word[topi.item()])\n\n            decoder_input = topi.squeeze().detach()\n\n        return decoded_words, decoder_attentions[:di + 1]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can evaluate random sentences from the training set and print out the\ninput, target, and output to make some subjective quality judgements:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def evaluateRandomly(encoder, decoder, n=10):\n    for i in range(n):\n        pair = random.choice(pairs)\n        print('>', pair[0])\n        print('=', pair[1])\n        output_words, attentions = evaluate(encoder, decoder, pair[0])\n        output_sentence = ' '.join(output_words)\n        print('<', output_sentence)\n        print('')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Training and Evaluating\n=======================\n\nWith all these helper functions in place (it looks like extra work, but\nit makes it easier to run multiple experiments) we can actually\ninitialize a network and start training.\n\nRemember that the input sentences were heavily filtered. For this small\ndataset we can use relatively small networks of 256 hidden nodes and a\nsingle GRU layer. After about 40 minutes on a MacBook CPU we'll get some\nreasonable results.\n\n.. Note::\n   If you run this notebook you can train, interrupt the kernel,\n   evaluate, and continue training later. Comment out the lines where the\n   encoder and decoder are initialized and run ``trainIters`` again.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "hidden_size = 256\nencoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device)\nattn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)\n\ntrainIters(encoder1, attn_decoder1, 75000, print_every=5000)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "evaluateRandomly(encoder1, attn_decoder1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Visualizing Attention\n---------------------\n\nA useful property of the attention mechanism is its highly interpretable\noutputs. Because it is used to weight specific encoder outputs of the\ninput sequence, we can imagine looking where the network is focused most\nat each time step.\n\nYou could simply run ``plt.matshow(attentions)`` to see attention output\ndisplayed as a matrix, with the columns being input steps and rows being\noutput steps:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "output_words, attentions = evaluate(\n    encoder1, attn_decoder1, \"je suis trop froid .\")\nplt.matshow(attentions.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "For a better viewing experience we will do the extra work of adding axes\nand labels:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def showAttention(input_sentence, output_words, attentions):\n    # Set up figure with colorbar\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    cax = ax.matshow(attentions.numpy(), cmap='bone')\n    fig.colorbar(cax)\n\n    # Set up axes\n    ax.set_xticklabels([''] + input_sentence.split(' ') +\n                       ['<EOS>'], rotation=90)\n    ax.set_yticklabels([''] + output_words)\n\n    # Show label at every tick\n    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n    plt.show()\n\n\ndef evaluateAndShowAttention(input_sentence):\n    output_words, attentions = evaluate(\n        encoder1, attn_decoder1, input_sentence)\n    print('input =', input_sentence)\n    print('output =', ' '.join(output_words))\n    showAttention(input_sentence, output_words, attentions)\n\n\nevaluateAndShowAttention(\"elle a cinq ans de moins que moi .\")\n\nevaluateAndShowAttention(\"elle est trop petit .\")\n\nevaluateAndShowAttention(\"je ne crains pas de mourir .\")\n\nevaluateAndShowAttention(\"c est un jeune directeur plein de talent .\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Exercises\n=========\n\n-  Try with a different dataset\n\n   -  Another language pair\n   -  Human \u2192 Machine (e.g. IOT commands)\n   -  Chat \u2192 Response\n   -  Question \u2192 Answer\n\n-  Replace the embeddings with pre-trained word embeddings such as word2vec or\n   GloVe\n-  Try with more layers, more hidden units, and more sentences. Compare\n   the training time and results.\n-  If you use a translation file where pairs have two of the same phrase\n   (``I am test \\t I am test``), you can use this as an autoencoder. Try\n   this:\n\n   -  Train as an autoencoder\n   -  Save only the Encoder network\n   -  Train a new Decoder for translation from there\n\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.8"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}